package com.gupao.javavip.concurrent.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ConfigLoader {
    private static volatile int EXPORT_MODEL = 1;

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static void startConfigMonitor() {
        Thread config_monitor = new Thread(() -> {
            for (; ; ) {
                updateExportModel();
                try {
                    TimeUnit.SECONDS.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        config_monitor.start();
    }

    public static void updateExportModel() {
        lock.writeLock().lock();
        try {
            Long currentSecond = System.currentTimeMillis() / 1000;
            EXPORT_MODEL = currentSecond % 2 == 0 ? 1 : 0;

            System.out.println(currentSecond + " config_monitor executing:" + EXPORT_MODEL);
        } finally {
            lock.writeLock().unlock();
        }
    }

    public static int getExportModelConfig() {
        lock.readLock().lock();
        try {
            return EXPORT_MODEL;
        } finally {
            lock.readLock().unlock();
        }
    }
}
